package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Visitor;
import cn.wolfcode.luowowo.query.VisitorQuery;
import cn.wolfcode.luowowo.repository.VisitorRepository;
import cn.wolfcode.luowowo.service.IVisitorService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service

public class VisitorServiceImpl implements IVisitorService {

    @Autowired
    private VisitorRepository repository;

    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Visitor visitor) {

        visitor.setId(null);
        repository.save(visitor);
    }

    @Override
    public void delete(String id) {

        repository.deleteById(id);
    }

    @Override
    public void update(Visitor visitor) {

        repository.save(visitor);
    }

    @Override
    public Visitor get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Visitor> listAll() {
        return repository.findAll();
    }

    //区域分页查询(高级查询)
    @Override
    public Page<Visitor> query(VisitorQuery qo) {

        Query query = new Query();

        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,
                qo.getPageSize(), Sort.Direction.ASC,"_id");

        return DBHelper.query(template,Visitor.class,query,pageable);
    }

    // 添加按钮:添加/更新
    @Override
    public void saveOrUpdate(Visitor visitor) {
        if(StringUtils.hasLength(visitor.getId())){
            // 调用本类中的更新方法
            // 特殊案例,页面更新数据,刚好更集合中字段个数一直
            // 所以这种等价于全量更新(只有符合以上可以这么使用)
            this.update(visitor);//更新
        }else{
            this.save(visitor);//添加
        }
    }


}
